<template>
  <div class="order-payment">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>产品库存统计</h1>
      <div class="breadcrumb">产品库存统计</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>仓库名称</label>
          <input v-model="searchForm.warehouseName" type="text" placeholder="请输入仓库名称" />
        </div>
        <div class="form-item">
          <label>商品名称</label>
          <input v-model="searchForm.productName" type="text" placeholder="请输入商品名称" />
        </div>
        <div class="form-item">
          <label>规格编号</label>
          <input v-model="searchForm.specification" type="text" placeholder="请输入规格编号" />
        </div>
        <div class="form-item">
          <label>商品编码</label>
          <input v-model="searchForm.skuName" type="text" placeholder="请输入商品编码" />
        </div>
        <div class="form-item">
          <label>库存状态</label>
          <select v-model="searchForm.stockStatus">
            <option value="">全部</option>
            <option value="sufficient">库存充足</option>
            <option value="insufficient">库存不足</option>
            <option value="zero">零库存</option>
          </select>
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="searchInventory" :disabled="loading">查询</button>
          <button class="btn btn-secondary" @click="resetSearch" :disabled="loading">重置</button>
          <button class="btn btn-success" @click="exportData" :disabled="loading">导出</button>
        </div>
      </div>
    </div>

    <!-- 库存列表 -->
    <div class="table-container">
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>
      <table class="data-table">
        <thead>
        <tr>
          <th>商品编码</th>
          <th>商品名称</th>
          <th>商品分类</th>
          <th>仓库名称</th>
          <th>库位</th>
          <th>批次号</th>
          <th>有效期</th>
          <th>在库数量</th>
          <th>可用数量</th>
          <th>占用数量</th>
          <th>单位成本</th>
          <th>库存总价值</th>
          <th>库存状态</th>
          <th>更新时间</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in inventoryList" :key="item.id">
          <td>{{ item.skuCode || '-' }}</td>
          <td>{{ item.skuName || '-' }}</td>
          <td>{{ item.categoryName || '-' }}</td>
          <td>{{ item.warehouseName || '-' }}</td>
          <td>{{ item.locationName || '-' }}</td>
          <td>{{ item.batchNo || '-' }}</td>
          <td>{{ formatDate(item.expiryDate) }}</td>
          <td class="quantity-text">{{ formatNumber(item.onHandQty) }}</td>
          <td class="quantity-text">{{ formatNumber(item.availableQty) }}</td>
          <td class="quantity-text">{{ formatNumber(item.occupiedQty) }}</td>
          <td class="cost-text">¥{{ formatNumber(item.unitCost) }}</td>
          <td class="value-text">¥{{ formatNumber(item.totalValue) }}</td>
          <td>
            <span :class="getStockStatusClass(item.stockStatus)">
              {{ getStockStatusText(item.stockStatus) }}
            </span>
          </td>
          <td>{{ formatDateTime(item.updatedAt) }}</td>
        </tr>
        <tr v-if="inventoryList.length === 0">
          <td colspan="13" class="text-center">暂无数据</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="totalItems > 0">
      <div class="pagination-info">
        共{{ totalPages }}页/{{ totalItems }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-page" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">上一页</button>
        <button
            v-for="page in visiblePages"
            :key="page"
            class="btn btn-page"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button class="btn btn-page" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">下一页</button>
      </div>
      <div class="pagination-jump">
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="totalPages" />
        <span>页</span>
        <button class="btn btn-small" @click="jumpToPage">确定</button>
      </div>
    </div>
  </div>

</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet } from '../../utils/api.js'

// 查询条件
const searchForm = reactive({
  warehouseName: '',
  productName: '',
  specification: '',
  skuName: '',
  stockStatus: ''
})

// 列表与分页
const inventoryList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalItems = ref(0)
const jumpPage = ref(1)
const loading = ref(false)


// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

// 方法
const searchInventory = async () => {
  await loadInventoryData()
}

const resetSearch = async () => {
  searchForm.warehouseName = ''
  searchForm.productName = ''
  searchForm.specification = ''
  searchForm.skuName = ''
  searchForm.stockStatus = ''
  currentPage.value = 1
  await loadInventoryData()
}

const changePage = async (page) => {
  currentPage.value = page
  await loadInventoryData()
}

const jumpToPage = async () => {
  if (jumpPage.value >= 1 && jumpPage.value <= totalPages.value) {
    currentPage.value = jumpPage.value
    await loadInventoryData()
  }
}

const formatDate = (v) => {
  if (!v) return '-'
  const d = new Date(v)
  if (isNaN(d.getTime())) return '-'
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`
}

const formatDateTime = (v) => {
  if (!v) return '-'
  const d = new Date(v)
  if (isNaN(d.getTime())) return '-'
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

const formatNumber = (value) => {
  if (value == null) return '0'
  return Number(value).toLocaleString()
}

const getStockStatusText = (status) => {
  const textMap = {
    'sufficient': '库存充足',
    'insufficient': '库存不足',
    'zero': '零库存'
  }
  return textMap[status] || '未知'
}

const getStockStatusClass = (status) => {
  const classMap = {
    'sufficient': 'status-success',
    'insufficient': 'status-warning',
    'zero': 'status-danger'
  }
  return classMap[status] || 'status-info'
}

const exportData = async () => {
  try {
    const params = {
      ...searchForm,
      page: 1,
      size: 10000 // 导出所有数据
    }

    const response = await fetch('/api/ware-service/ware/inventory-stats/export', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(params)
    })

    if (!response.ok) {
      throw new Error(`导出失败: ${response.status}`)
    }

    // 创建下载链接
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `库存统计报表_${new Date().toISOString().slice(0, 10)}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    alert('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    alert('导出失败: ' + error.message)
  }
}

const loadInventoryData = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: currentPage.value,
      size: pageSize.value,
      ...(searchForm.productName && { skuName: searchForm.productName }),
      ...(searchForm.specification && { specification: searchForm.specification }),
      ...(searchForm.warehouseName && { warehouseName: searchForm.warehouseName }),
      ...(searchForm.skuName && { skuName: searchForm.skuName }),
      ...(searchForm.stockStatus && { stockStatus: searchForm.stockStatus })
    })

    const response = await apiGet(`/ware-service/ware/inventory-stats/list?${params}`)
    
    if (response && response.code === 200 && response.data) {
      inventoryList.value = response.data.records || []
      totalItems.value = response.data.total || 0
      totalPages.value = Math.ceil(totalItems.value / pageSize.value)
      currentPage.value = response.data.current || currentPage.value
    } else {
      console.error('获取库存列表失败:', response?.message || '未知错误')
      inventoryList.value = []
      totalItems.value = 0
      totalPages.value = 1
    }
  } catch (error) {
    console.error('加载库存数据失败:', error)
    inventoryList.value = []
    totalItems.value = 0
    totalPages.value = 1
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadInventoryData()
})
</script>

<style scoped>
.order-payment {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: flex-end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-item input,
.form-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.form-buttons {
  display: flex;
  gap: 10px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  overflow-x: auto;
  margin-bottom: 20px;
  position: relative;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.status-success {
  color: #28a745;
  font-weight: 500;
}

.status-warning {
  color: #ffc107;
  font-weight: 500;
}

.status-danger {
  color: #dc3545;
  font-weight: 500;
}

.status-info {
  color: #6c757d;
  font-weight: 500;
}

.quantity-text {
  font-weight: 500;
  color: #007bff;
}

.cost-text {
  font-weight: 500;
  color: #28a745;
}

.value-text {
  font-weight: 600;
  color: #fd7e14;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-jump input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover {
  background: #c82333;
}

.btn-page {
  background: white;
  border: 1px solid #ddd;
  color: #333;
  padding: 6px 12px;
}

.btn-page:hover {
  background: #f8f9fa;
}

.btn-page.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn:disabled:hover {
  background: inherit;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 1000px;
  max-width: 95vw;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.summary-bar {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  background: #eef1f6;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
}
.summary-item .label { color: #666; font-size: 12px; }
.summary-item .value { color: #333; font-size: 16px; }
.summary-item .value.strong { font-weight: 600; }

.tabs { margin-top: 12px; }
.tabs-bar { display: flex; gap: 8px; margin-bottom: 12px; }
.tab-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
}
.tab-btn.active { background: #4c8dff; color: #fff; border-color: #4c8dff; }


.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  height: 80px;
  resize: vertical;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
